import React, { useContext, useEffect, useState } from "react";
import {
  Box,
  Button,
  Flex,
  useDisclosure,
  AlertDialog,
  AlertDialogOverlay,
  AlertDialogContent,
  AlertDialogHeader,
  AlertDialogBody,
  AlertDialogFooter,
  Popover,
  PopoverTrigger,
  PopoverContent,
  PopoverBody,
  PopoverArrow,
  Image,
  useToast,
} from "@chakra-ui/react";
import { MainContext } from "@/src/providers/MainProvider";
import MouseComponent from "../Common/MouseComponent";
import MouseKeyEdit from "./MouseKeyEdit";
import type { KeyLayout, MouseKey as IMouseKey } from "@/src/types/types.v1.d";
import { useTranslation } from "@/src/i18n";

const MouseKey = () => {
  const {
    mouseKeys,
    mouseLayout,
    selKeyIndex,
    setSelKeyIndex,
    connectedMouse,
    resetSingleKey,
    resetAllMouseKeys,
    setMouseKeys,
    profile,
    profileIndex,
  } = useContext(MainContext);

  const toast = useToast();
  const [nowIndex, setNowIndex] = useState<string | null>(null);
  const { isOpen, onOpen, onClose } = useDisclosure();
  const cancelRef = React.useRef<HTMLButtonElement>(null);

  const [openPopoverIndex, setOpenPopoverIndex] = React.useState<number | null>(
    null
  );

  const { t } = useTranslation("");
  const handleKeyClick = (keyIndex: number) => {
    console.log("选中按键:", keyIndex);
    setSelKeyIndex(keyIndex);
  };

  const handleResetKey = (index: number) => {
    setOpenPopoverIndex(null);
    setSelKeyIndex(-1);
    console.log("重置按键:", index);
    resetSingleKey(connectedMouse, index);
  };

  const restAllKey = () => {
    onClose();
    setSelKeyIndex(-1);
    resetAllMouseKeys(connectedMouse);
  };

  if (!mouseKeys || mouseKeys.length === 0) {
    return null;
  }

  // 是否恢复默认
  const isResetDefault = (index: number) => {
    if (index === 0) {
      return (
        mouseKeys[index]?.type === 0x20 && mouseKeys[index]?.code1 === 0x01
      );
    } else if (index === 1) {
      return (
        mouseKeys[index]?.type === 0x20 && mouseKeys[index]?.code1 === 0x02
      );
    } else if (index === 2) {
      return (
        mouseKeys[index]?.type === 0x20 && mouseKeys[index]?.code1 === 0x04
      );
    } else if (index === 3) {
      return (
        mouseKeys[index]?.type === 0x20 && mouseKeys[index]?.code1 === 0x08
      );
    } else if (index === 4) {
      return (
        mouseKeys[index]?.type === 0x20 && mouseKeys[index]?.code1 === 0x10
      );
    } else if (index === 5) {
      return (
        mouseKeys[index]?.type === 0x21 && mouseKeys[index]?.code1 === 0x55
      );
    } else if (index === 6) {
      return (
        mouseKeys[index]?.type === 0x21 &&
        mouseKeys[index]?.code1 === 0x38 &&
        mouseKeys[index]?.code2 === 0x01
      );
    } else if (index === 7) {
      return (
        mouseKeys[index]?.type === 0x21 &&
        mouseKeys[index]?.code1 === 0x38 &&
        mouseKeys[index]?.code2 === 0xff
      );
    } else if (index === 8) {
      return (
        mouseKeys[index]?.type === 0x21 && mouseKeys[index]?.code1 === 0xaa
      );
    } else if (index === 9) {
      return (
        mouseKeys[index]?.type === 0x21 && mouseKeys[index]?.code1 === 0x61
      );
    } else if (index === 10) {
      return (
        mouseKeys[index]?.type === 0x30 &&
        mouseKeys[index]?.code1 === 0x94 &&
        mouseKeys[index]?.code2 === 0x01
      );
    } else if (index === 11) {
      return (
        mouseKeys[index]?.type === 0x10 &&
        mouseKeys[index]?.code1 === 0x08 &&
        mouseKeys[index]?.code2 === 0x07
      );
    } else if (index === 12) {
      return (
        mouseKeys[index]?.type === 0x10 && mouseKeys[index]?.code2 === 0x1e
      );
    } else if (index === 13) {
      return (
        mouseKeys[index]?.type === 0x10 && mouseKeys[index]?.code2 === 0x1f
      );
    } else if (index === 14) {
      return (
        mouseKeys[index]?.type === 0x10 && mouseKeys[index]?.code2 === 0x20
      );
    } else if (index === 15) {
      return (
        mouseKeys[index]?.type === 0x10 && mouseKeys[index]?.code2 === 0x21
      );
    } else if (index === 16) {
      return (
        mouseKeys[index]?.type === 0x10 && mouseKeys[index]?.code2 === 0x22
      );
    } else if (index === 17) {
      return (
        mouseKeys[index]?.type === 0x10 && mouseKeys[index]?.code2 === 0x23
      );
    }

    return false;
  };

  // 是否全部是默认
  const isAllDefault = () => {
    return mouseKeys.every((key) => isResetDefault(key.index));
  };

  const dropKey = (e: any, index: number) => {
    console.log("dropKey", e.dataTransfer.getData("keyCode"));
    if (index == 0) {
      toast({
        title: t("leftBtnNoChange"),
        status: "info",
        duration: 3000,
        isClosable: true,
        colorScheme: "blue",
        position: "top",
      });
      return;
    }
    const keyInfo: IMouseKey = JSON.parse(e.dataTransfer.getData("keyCode"));
    console.log("keyInfo", keyInfo, "index", index);
    const newKey = {
      ...mouseKeys[index],
      keyName: keyInfo.keyName,
      type: keyInfo.type,
      code1: keyInfo.code1,
      code2: keyInfo.code2,
      code3: keyInfo.code3,
    };

    const updatedMouseKeys = mouseKeys.map((key) =>
      key.index === index ? newKey : key
    );

    setMouseKeys(updatedMouseKeys);
    profile.updateMouseKeys(profileIndex, updatedMouseKeys);
    if (connectedMouse) {
      connectedMouse.setMouseKeys(updatedMouseKeys, profileIndex);
    }
    toast({
      title: `${t("haveSet")}：${
        keyInfo.type === 0x70 ? keyInfo.keyName : t(keyInfo.keyName)
      }`,
      status: "info",
      duration: 3000,
      isClosable: true,
      colorScheme: "blue",
      position: "top",
    });
  };
  return (
    <Box pl="0px" pr="0px" pb="0px" height="100%" className="select-none">
      <Flex height="100%">
        {selKeyIndex >= 0 && (
          <Box flex="1" borderColor="gray.200">
            <MouseKeyEdit />
          </Box>
        )}
        <Box
          flex={selKeyIndex >= 0 ? "2" : "1"}
          display="flex"
          position="relative"
          height="100%"
          overflow="hidden"
        >
          <Box
            position="absolute"
            left="50%"
            top="50%"
            sx={{
              transform: "translate(-50%, -50%)",
            }}
            display="flex"
            flexDirection="column"
            alignItems="center"
            gap="0px"
          >
            {mouseLayout.map((keyInfo: KeyLayout, index) => (
              <React.Fragment key={index}>
                <Popover
                  placement="bottom"
                  trigger="hover"
                  isOpen={!isResetDefault(index) && openPopoverIndex === index}
                  onOpen={() =>
                    !isResetDefault(index) && setOpenPopoverIndex(index)
                  }
                  onClose={() => setOpenPopoverIndex(null)}
                >
                  <PopoverTrigger>
                    <Box
                      className={`common-key ${
                        selKeyIndex === index ? "key-actived" : ""
                      }`}
                      position="absolute"
                      left={`${keyInfo?.keyLeft}px`}
                      right={`${keyInfo?.keyRight}px`}
                      top={`${keyInfo.keyTop}px`}
                      color="white"
                      display="flex"
                      alignItems="center"
                      justifyContent="center"
                      cursor="pointer"
                      onDrop={(evt) => dropKey(evt, index)}
                      onDragOver={(e) => e.preventDefault()}
                      onClick={() => handleKeyClick(index)}
                    >
                      <Box
                        sx={{
                          paddingLeft: "16px",
                          paddingRight: "16px",
                          overflow: "hidden",
                          whiteSpace: "nowrap",
                          textAlign: "center",
                        }}
                      >
                        {t(mouseKeys[index]?.keyName)}
                      </Box>
                    </Box>
                  </PopoverTrigger>
                  <PopoverContent width="120px">
                    <PopoverBody px={0} py={1}>
                      <Button
                        width="100%"
                        size="sm"
                        color="#ffffff"
                        fontSize="14px"
                        opacity={0.6}
                        _hover={{
                          color: "white",
                          backgroundColor: "#0066ee",
                          opacity: 1,
                          padding: "4px 8px",
                          borderRadius: "4px",
                          fontSize: "14px",
                        }}
                        variant="ghost"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleResetKey(index);
                        }}
                      >
                        {t("restoreDefault")}
                      </Button>
                    </PopoverBody>
                  </PopoverContent>
                </Popover>
                <Box
                  position="absolute"
                  left={`${keyInfo.line1Left}px`}
                  top={`${keyInfo.line1Top}px`}
                  width={`${keyInfo.line1Width}px`}
                  height="1px"
                  transform={`rotate(${keyInfo.line1Rotate}deg)`}
                  backgroundColor={
                    selKeyIndex === index ? "#0066ff" : "#d7dee3"
                  }
                />
                <Box
                  position="absolute"
                  left={`${keyInfo.line2Left}px`}
                  top={`${keyInfo.line2Top}px`}
                  width={`${keyInfo.line2Width}px`}
                  height="1px"
                  transform={`rotate(${keyInfo.line2Rotate}deg)`}
                  backgroundColor={
                    selKeyIndex === index ? "#0066ff" : "#d7dee3"
                  }
                />
              </React.Fragment>
            ))}
            <MouseComponent />

            <Button
              height="40px"
              borderRadius="8px"
              border="1px solid"
              borderColor={"#151515"}
              disabled={isAllDefault()}
              opacity={isAllDefault() ? 0.4 : 1}
              backgroundColor="white"
              color={"#151515"}
              fontSize="14px"
              fontWeight={400}
              _hover={{
                cursor: isAllDefault() ? "not-allowed" : "pointer",
                backgroundColor: "white",
              }}
              _disabled={{
                cursor: "not-allowed",
                pointerEvents: "none",
                opacity: 0.4,
              }}
              onClick={isAllDefault() ? undefined : onOpen}
              mt="20px"
            >
              {t("restAllDefault")}
            </Button>
          </Box>
        </Box>
      </Flex>

      <AlertDialog
        isOpen={isOpen}
        leastDestructiveRef={cancelRef}
        onClose={onClose}
      >
        <AlertDialogOverlay>
          <AlertDialogContent
            mx="auto"
            my="auto"
            maxW="400px"
            width="430px"
            height="300px"
          >
            <AlertDialogHeader
              display="flex"
              justifyContent="space-between"
              alignItems="center"
              // bg="#211a31"
              height="48px"
              px="24px"
              fontSize="16px"
            >
              {t("tips")}
              <Box as="button" onClick={onClose} _hover={{ opacity: 0.8 }}>
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                  <path
                    d="M12.8536 2.85355C13.0488 2.65829 13.0488 2.34171 12.8536 2.14645C12.6583 1.95118 12.3417 1.95118 12.1464 2.14645L7.5 6.79289L2.85355 2.14645C2.65829 1.95118 2.34171 1.95118 2.14645 2.14645C1.95118 2.34171 1.95118 2.65829 2.14645 2.85355L6.79289 7.5L2.14645 12.1464C1.95118 12.3417 1.95118 12.6583 2.14645 12.8536C2.34171 13.0488 2.65829 13.0488 2.85355 12.8536L7.5 8.20711L12.1464 12.8536C12.3417 13.0488 12.6583 13.0488 12.8536 12.8536C13.0488 12.6583 13.0488 12.3417 12.8536 12.1464L8.20711 7.5L12.8536 2.85355Z"
                    fill="currentColor"
                  />
                </svg>
              </Box>
            </AlertDialogHeader>

            <AlertDialogBody
              textAlign="center"
              color="white"
              pt="20px"
              pb="20px"
              px="20px"
              display="flex"
              flexDirection="column"
              alignItems="center"
            >
              <Box mb="5px" display="flex" justifyContent="center" width="100%">
                <Image
                  src="./svgs/icon_error.svg"
                  alt="error"
                  width="40px"
                  height="40px"
                />
              </Box>

              {t("restAllDefaultComfirm")}
            </AlertDialogBody>

            <AlertDialogFooter justifyContent="center" gap="10px" pb="10px">
              <Button
                bg="#EA5E56"
                color="white"
                _hover={{ bg: "#d65249" }}
                _active={{ bg: "#c94b43" }}
                ref={cancelRef}
                onClick={restAllKey}
                width="80px"
                height="40px"
              >
                {t("reset")}
              </Button>
              <Button
                variant="outline"
                color="white"
                ref={cancelRef}
                onClick={onClose}
                width="80px"
                height="40px"
              >
                {t("cancel")}
              </Button>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialogOverlay>
      </AlertDialog>
    </Box>
  );
};

export default MouseKey;
